import tkinter as tk
from tkinter import ttk, messagebox
import csv
import time

import requests
import urllib.parse
import re

wait_for_get_request = [


		'https://www.facebook.com/share/p/16GPL4TYs5/','5nian',
		'https://www.facebook.com/share/p/18rMxmxVJv/','35zhou',
		'https://www.facebook.com/share/p/1XhCDn6f5X/','3nian'
	    'https://www.facebook.com/share/p/15u63UjsB3/','4nian',
		'https://www.facebook.com/share/p/1BLrvNA6Fk/','35zhou'
]
def is_valid_url(url):

	regex = re.compile(
		r'^(?:http)s?://'  # http:// 或 https://
		r'(?:\S+(?::\S*)?@)?'  # 用户名密码（如 user:pass@）
		r'(?:[A-Za-z0-9\-]+\.)+[A-Za-z]{2,}'  # 域名
		r'(?::\d+)?'  # 
		r'(?:/?|[/?]\S+)$', re.IGNORECASE
	)
	return re.match(regex, url) is not None


def snap(url):
	print("原始URL:", url)

	# 1. 校验URL格式
	if not is_valid_url(url):
		raise ValueError(f"Invalid URL format: {url}")

	# 2. 对URL进行编码
	encoded_url = urllib.parse.quote(url, safe=':/?&=')
	print("编码后URL:", encoded_url)

	org_url = "https://api.brightdata.com/datasets/v3/trigger"
	headers = {
		"Authorization": "YOUR_TOKEN",
		"Content-Type": "application/json",
	}
	params = {
		"dataset_id": "YOUR_DATASET_ID",
		"include_errors": "true",
	}
	data = {
		"deliver": {
			"type": "s3",
			"filename": {"template": "{[snapshot_id]}", "extension": "json"},
			"bucket": "lt",
			"directory": ""
		},
		"input": [{"url": encoded_url}],  # 使用编码后的URL
	}

	# 发送请求
	response = requests.post(org_url, headers=headers, params=params, json=data)

	return response.json()['snapshot_id']


def getRes(snap):
	URL = f"https://api.brightdata.com/datasets/v3/snapshot/{snap}"
	print(URL)
	headers = {
		"Authorization": "YOUR_TOKEN",
	}
	params = {
		"format": "json",
	}

	response = requests.get(url=URL, headers=headers, params=params)
	print(response.json())

	res = [{item['user_name']: item['comment_text'] for item in response.json() if
			'user_name' in item and 'comment_text' in item}]
	return res

def fetch_comments():
	url = entry.get().strip()
	if not url:
		messagebox.showwarning("输入错误", "请输入有效的网页链接！")
		return

	s = snap(url)
	print(s)
	time.sleep(300)
	comments = getRes(s)
	print(comments)

	# 清空表格内容
	for row in tree.get_children():
		tree.delete(row)

	# 插入新数据
	for comment in comments:
		for name, text in comment.items():
			tree.insert("", "end", values=(name, text))


def save_to_csv():
	filename = "comments.csv"
	with open(filename, mode="w", newline="", encoding="utf-8") as file:
		writer = csv.writer(file)
		writer.writerow(["姓名", "评论内容"])
		for row in tree.get_children():
			writer.writerow(tree.item(row, "values"))
	messagebox.showinfo("保存成功", f"评论内容已保存到 {filename}")


# 创建主窗口
root = tk.Tk()
root.title("facebook数据抓取工具")
root.geometry("800x500")
root.configure(bg="#E6F0FF")  # 背景颜色浅蓝色

# 输入框和按钮框架
frame_top = tk.Frame(root, bg="#E6F0FF")
frame_top.pack(pady=10, padx=10, fill="x")

entry = tk.Entry(frame_top, font=("Arial", 12), width=40)
entry.pack(side="left", padx=5, pady=5, expand=True, fill="x")

btn_fetch = tk.Button(frame_top, text="抓取数据", font=("Arial", 12), bg="#007BFF", fg="white", command=fetch_comments)
btn_fetch.pack(side="right", padx=5, pady=5)

btn_save = tk.Button(root, text="保存为CSV", font=("Arial", 12), bg="#28A745", fg="white", command=save_to_csv)
btn_save.pack(anchor="ne", padx=10, pady=5)

# 结果展示表格
frame_table = tk.Frame(root, bg="#E6F0FF")
frame_table.pack(pady=10, padx=10, fill="both", expand=True)

columns = ("姓名", "评论内容")
tree = ttk.Treeview(frame_table, columns=columns, show="headings")
tree.heading("姓名", text="姓名")
tree.heading("评论内容", text="评论内容")
tree.column("姓名", width=150, anchor="center")
tree.column("评论内容", width=300, anchor="w")

# 添加滚动条
scrollbar = ttk.Scrollbar(frame_table, orient="vertical", command=tree.yview)
tree.configure(yscroll=scrollbar.set)
scrollbar.pack(side="right", fill="y")
tree.pack(fill="both", expand=True)

# 运行应用
root.mainloop()